using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using Sirenix.OdinInspector;
using UnityEditor;

public class AutoScanner : MonoBehaviour
{
    public ScannerConfig scannerConfig;
    public ScannerRuntime scannerRuntime;

    [BoxGroup("颜色")] public Color baseColor = Color.green;
    [BoxGroup("颜色")] public Color boundColor = new Color(0, 0, 0, 0.1f);
    [BoxGroup("颜色")] public Color collideColor = Color.red;
    [BoxGroup("颜色")] public Color leaderRangeColor = new Color(0, 0.5f, 1f, 0.3f);
    [BoxGroup("颜色")] public Color directionRetentionColor = new Color(0.8f, 0.4f, 0, 0.8f);
    public string UavName = "UAV1";

    [BoxGroup("拖尾效果")] [HideInInspector] public bool enableTrail = true; // 由控制面板控制
    [BoxGroup("拖尾效果")] public int maxTrailPoints = 50;
    [BoxGroup("拖尾效果")] public float trailDistance = 5f; // 拖尾消失距离
    [BoxGroup("拖尾效果")] public Color trailColor = new Color(1f, 0.5f, 0f, 0.8f); // 橙色拖尾

    private Vector3 _initialPosition; // 保存初始位置
    private List<Vector3> _trailPoints = new List<Vector3>(); // 轨迹点列表
    private float _lastTrailUpdateTime = 0f;
    private const float TRAIL_UPDATE_INTERVAL = 0.1f; // 每0.1秒记录一个点

    private void Awake()
    {
        // 自动创建数据实例（如果未指定）
        if (scannerConfig == null)
        {
            scannerConfig = ScannerDataSerializer.CreateDefaultConfigData();
            Debug.LogWarning("自动创建了ScannerConfigData实例");
        }

        if (scannerRuntime == null)
        {
            scannerRuntime = ScannerDataSerializer.CreateDefaultRuntimeData();
            Debug.LogWarning("自动创建了ScannerRuntimeData实例");
        }
    }

    private void Start()
    {
        // 保存初始位置
        _initialPosition = transform.position;

        // 初始化方向向量
        scannerRuntime.scoreDir = transform.forward;
        scannerRuntime.pathDir = transform.forward;
        scannerRuntime.collideDir = Vector3.zero;
        scannerRuntime.leaderRangeDir = Vector3.zero;
        scannerRuntime.directionRetentionDir = transform.forward;
        scannerRuntime.finalMoveDir = transform.forward;

        scannerRuntime.uavname = UavName;
        
        // 初始化轨迹点（记录初始位置）
        _trailPoints.Clear();
        _trailPoints.Add(transform.position);
        _lastTrailUpdateTime = Time.time;
    }

    /// <summary>
    /// 重置无人机位置到初始点
    /// </summary>
    public void ResetPosition()
    {
        // transform.position = _initialPosition;

        // 重置方向向量
        scannerRuntime.scoreDir = transform.forward;
        scannerRuntime.pathDir = transform.forward;
        scannerRuntime.collideDir = Vector3.zero;
        scannerRuntime.leaderRangeDir = Vector3.zero;
        scannerRuntime.directionRetentionDir = transform.forward;
        scannerRuntime.finalMoveDir = transform.forward;

        // 清除轨迹点
        _trailPoints.Clear();
        _trailPoints.Add(transform.position);

        Debug.Log($"[重置] {UavName} 已重置到初始位置: {_initialPosition}");
    }


    public void OnInitConfig(ScannerConfig config)
    {
        Debug.Log("接受到配置数据" + config.ToString());
        scannerConfig.CopyByData(config);
    }

    public void OnInit(ScannerRuntime data)
    {
        scannerRuntime.CopyByData(data);
    }

    private void Update()
    {
        if (OptimizedHexGrid.Instance == null || scannerConfig == null || scannerRuntime == null) return;

        // 更新运行时位置信息（同步本地位置到运行时数据）
        scannerRuntime.uavname = UavName;
        scannerRuntime.position = transform.position;
        scannerRuntime.forward = transform.forward;
        scannerRuntime.leaderPosition = LeaderController.Instance?.CurrentPosition ?? Vector3.zero;
        scannerRuntime.leaderScanRadius = LeaderController.Instance?.scanRadius ?? 0;

        // 执行扫描（仅更新网格状态，不参与算法计算）
        OptimizedHexGrid.Instance.ScanAreaDecrease(transform.position, scannerConfig.scanRadius);

        // 更新其他扫描器位置（提供给外部算法）
        UpdateOtherScannerPositions();
        
        // 更新轨迹点
        UpdateTrail();
    }
    
    /// <summary>
    /// 更新轨迹点
    /// </summary>
    private void UpdateTrail()
    {
        // 从控制面板获取拖尾开关
        bool trailEnabled = GizmosControlPanel.Instance == null || GizmosControlPanel.Instance.showTrail;
        if (!trailEnabled) return;
        
        // 按时间间隔记录轨迹点
        if (Time.time - _lastTrailUpdateTime >= TRAIL_UPDATE_INTERVAL)
        {
            _trailPoints.Add(transform.position);
            _lastTrailUpdateTime = Time.time;
            
            // 限制最大点数
            if (_trailPoints.Count > maxTrailPoints)
            {
                _trailPoints.RemoveAt(0);
            }
            
            // 移除距离当前位置太远的点（从旧到新遍历）
            Vector3 currentPos = transform.position;
            for (int i = 0; i < _trailPoints.Count; i++)
            {
                float distance = Vector3.Distance(currentPos, _trailPoints[i]);
                if (distance > trailDistance)
                {
                    _trailPoints.RemoveAt(i);
                    i--; // 移除后索引回退
                }
            }
        }
    }

    /// <summary>
    /// 更新其他扫描器的位置信息（提供给外部算法）
    /// </summary>
    private void UpdateOtherScannerPositions()
    {
        if (scannerRuntime.otherScannerPositions == null)
            scannerRuntime.otherScannerPositions = new List<Vector3>();
        else
            scannerRuntime.otherScannerPositions.Clear();

        var otherScanners = FindObjectsOfType<AutoScanner>()
            .Where(s => s != this && s.gameObject.activeInHierarchy)
            .ToArray();

        foreach (var scanner in otherScanners)
        {
            scannerRuntime.otherScannerPositions.Add(scanner.transform.position);
        }
    }

    [Button]
    public void TestPOut(string path = "Assets/StreamingAssets/")
    {
        System.IO.File.WriteAllText(path + "runtimeData.json",
            ScannerDataSerializer.SerializeScannerRunTimeData(scannerRuntime));
        System.IO.File.WriteAllText(path + "config.json",
            ScannerDataSerializer.SerializeScannerConfigData(scannerConfig));
        Debug.Log($"数据已保存到: {path}");
    }


    // Gizmos绘制（保留所有可视化效果）
    private void OnDrawGizmos()
    {
#if UNITY_EDITOR
        if (scannerConfig == null || scannerRuntime == null) return;

        // 从控制面板获取显示设置
        bool showScan = GizmosControlPanel.Instance == null || GizmosControlPanel.Instance.showScanRange;
        bool showRepulsion = GizmosControlPanel.Instance != null && GizmosControlPanel.Instance.showRepulsionRange;
        bool showDirections = GizmosControlPanel.Instance == null || GizmosControlPanel.Instance.showDirectionVectors;
        bool showTrail = GizmosControlPanel.Instance == null || GizmosControlPanel.Instance.showTrail;

        // 绘制扫描范围
        if (showScan)
        {
            Handles.color = baseColor;
            Handles.DrawWireDisc(transform.position, Vector3.up, scannerConfig.scanRadius);
            // Handles.Label(transform.position + Vector3.up * (scannerConfig.scanRadius + 0.3f),
            //     $"扫描范围: {scannerConfig.scanRadius}m",
                // new GUIStyle { normal = { textColor = baseColor } });
            Handles.Label(transform.position + Vector3.up * -0.3f, UavName,
                new GUIStyle { normal = { textColor = Color.green } });

            Handles.Label(transform.position + Vector3.up * -0.6f, "Unity坐标: " + transform.position);
            Handles.Label(transform.position + Vector3.up * -0.9f,
                "Airsim坐标: " + VectorTool.UnityToAirSim(transform.position));
        }

        // 绘制排斥力范围
        if (showRepulsion)
        {
            Handles.color = boundColor;
            Handles.DrawWireDisc(transform.position, Vector3.up, scannerConfig.maxRepulsionDistance);
        }

        // 绘制各方向向量
        if (showDirections)
        {
            var dirLength = 2f;

        // 熵值方向（绿色）
        if (scannerRuntime.scoreDir != Vector3.zero)
        {
            Handles.color = Color.green;
            var scoreEnd = transform.position + scannerRuntime.scoreDir * dirLength;
            Handles.DrawLine(transform.position, scoreEnd);
            Handles.DrawSolidDisc(scoreEnd, Vector3.up, 0.05f);
            Handles.Label(scoreEnd + Vector3.up * 0.2f, "熵值",
                new GUIStyle { normal = { textColor = Color.green } });
        }

        // 排斥方向（红色）
        if (scannerRuntime.collideDir != Vector3.zero)
        {
            Handles.color = Color.red;
            var collideEnd = transform.position + scannerRuntime.collideDir * dirLength;
            Handles.DrawLine(transform.position, collideEnd);
            Handles.DrawSolidDisc(collideEnd, Vector3.up, 0.05f);
            Handles.Label(collideEnd + Vector3.up * 0.2f, "排斥",
                new GUIStyle { normal = { textColor = Color.red } });
        }

        // Leader范围方向（蓝色）
        if (scannerRuntime.leaderRangeDir != Vector3.zero)
        {
            Handles.color = leaderRangeColor;
            var leaderEnd = transform.position + scannerRuntime.leaderRangeDir * dirLength;
            Handles.DrawLine(transform.position, leaderEnd);
            Handles.DrawSolidDisc(leaderEnd, Vector3.up, 0.05f);
            Handles.Label(leaderEnd + Vector3.up * 0.2f, "Leader",
                new GUIStyle { normal = { textColor = leaderRangeColor } });
        }

        // 方向保持向量（橙色）
        if (scannerRuntime.directionRetentionDir != Vector3.zero)
        {
            Handles.color = directionRetentionColor;
            var retentionEnd = transform.position + scannerRuntime.directionRetentionDir * dirLength;
            Handles.DrawLine(transform.position, retentionEnd);
            Handles.DrawSolidDisc(retentionEnd, Vector3.up, 0.05f);
            Handles.Label(retentionEnd + Vector3.up * 0.2f, "保持方向",
                new GUIStyle { normal = { textColor = directionRetentionColor } });
        }

        // 最终方向（紫色）
        if (scannerRuntime.finalMoveDir != Vector3.zero)
        {
            Handles.color = Color.magenta;
            var dirEnd = transform.position + scannerRuntime.finalMoveDir * (dirLength + 1);
            Handles.DrawLine(transform.position, dirEnd);
            Handles.DrawSolidDisc(dirEnd, Vector3.up, 0.05f);
            Handles.Label(dirEnd + Vector3.up * 0.2f, "移动方向",
                new GUIStyle { normal = { textColor = Color.magenta } });
        }

        } // end if (showDirections)
        
        // 绘制运动轨迹拖尾
        if (showTrail)
        {
            DrawTrail();
        }
#endif
    }
    
    /// <summary>
    /// 绘制运动轨迹拖尾（线段）
    /// </summary>
    private void DrawTrail()
    {
#if UNITY_EDITOR
        // 从控制面板获取拖尾开关
        bool trailEnabled = GizmosControlPanel.Instance == null || GizmosControlPanel.Instance.showTrail;
        if (!trailEnabled || _trailPoints == null || _trailPoints.Count < 2) return;

        Vector3 currentPos = transform.position;
        
        // 从当前位置到最旧的轨迹点绘制线段
        Vector3 previousPoint = currentPos;
        
        for (int i = _trailPoints.Count - 1; i >= 0; i--)
        {
            Vector3 point = _trailPoints[i];
            float distance = Vector3.Distance(currentPos, point);
            
            // 如果距离超过消失距离，停止绘制
            if (distance > trailDistance) break;
            
            // 计算透明度（越远越透明，直到完全消失）
            float normalizedDistance = distance / trailDistance; // 0-1
            float alpha = 1f - normalizedDistance;
            
            // 设置线条颜色和透明度
            Color lineColor = trailColor;
            lineColor.a = alpha;
            Handles.color = lineColor;
            
            // 绘制线段（连接相邻的轨迹点）
            if (i < _trailPoints.Count - 1)
            {
                // 连接当前点和上一个点
                Handles.DrawLine(previousPoint, point);
            }
            else
            {
                // 第一条线段：从当前位置连接到最新的轨迹点
                Handles.DrawLine(currentPos, point);
            }
            
            previousPoint = point;
        }
#endif
    }
}